package com.soft.line.service.impl;

import com.soft.line.entity.AttachmentInfo;
import com.soft.line.filter.HttpRequestUtil;
import com.soft.line.filter.UserTokenDto;
import com.soft.line.mapper.AttachmentInfoMapper;
import com.soft.line.service.AttachMentInfoService;
import com.soft.line.util.WebToolUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.net.Inet4Address;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.*;

@Service
@Slf4j
public class AttachmentInfoServiceImpl implements AttachMentInfoService {

    private String[] docTypes = new String[]{
            "DOC", "DOCX", "XLS", "XLSX", "PPT", "PPTX", "PDF"
    };

    private String[] imgTypes = new String[]{
            "JPG", "JPEG", "PNG", "BMP"
    };

    /**
     * 文件上传路径  例如：D盘下的路径
     */
    @Value(value = "${uploadFileDir}")
    private String uploadFileDir;

    @Value("${uploadFileMapping}")
    private String uploadFileMappingUrl;

    @Value("${server.port}")
    private String port ;

    @Value( "${server.servlet.context-path}")
    private String context_path;


    @Autowired
    private AttachmentInfoMapper attachmentInfoMapper;

    @Override
    public List<AttachmentInfo> selectAll(String attachmentType, Integer cId) {
        List<AttachmentInfo> list = attachmentInfoMapper.selectAll(attachmentType, cId);
        List<AttachmentInfo> result = new ArrayList<AttachmentInfo>();
        try {
            for (AttachmentInfo ainfo : list) {
                String pathUrl = ainfo.getAttachmentUrl();
                pathUrl = WebToolUtils.getLocalIP() + ":" + port + context_path + "/" + uploadFileMappingUrl  + pathUrl;
                ainfo.setAttachmentUrl(pathUrl);
                result.add(ainfo);
            }
        } catch (UnknownHostException | SocketException e) {
            log.error(e.getMessage(), e);
        }
        return result;
    }

    @Override
    public void delete(Map<String, Object> map) {
        attachmentInfoMapper.deleteFileMap(map);
    }

    @Override
    public String save(MultipartFile file, String type, Integer cId) {
        String fileName = file.getOriginalFilename();
        String contentType = fileName.substring(fileName.lastIndexOf(".")+1).toUpperCase();
        String childPath = "";
        if (type.equals("1")) {
            childPath = "contract";
        } else if (type.equals("2")) {
            childPath = "certificate";
        }
        if (!Arrays.asList(docTypes).contains(contentType) && !Arrays.asList(imgTypes).contains(contentType)) {
            return "上传文件格式不正确";
        }

        //上传
        File uploadRootFileDir = new File(uploadFileDir);
        File fileDir = new File(uploadRootFileDir.getAbsolutePath(), childPath + File.separator + cId);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        //文件夹中已存在的文件
        File[] existingFiles = fileDir.listFiles();

        for (File existingFile : existingFiles) {
            //文件名一样就先删除
            if (existingFile.getName().equals(fileName)) {
                existingFile.delete();
            }
        }

        File newFile = new File(fileDir.getAbsolutePath(), fileName);
        try {
            file.transferTo(newFile);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
            return "上传文件失败";
        }
        String userName="admin";
        UserTokenDto userToken= HttpRequestUtil.getUserToken();
        if(userToken!=null){
            userName=userToken.getUserInfo().getUserName();
        }
        AttachmentInfo attachmentInfo = new AttachmentInfo();
        attachmentInfo.setAttachmentName(fileName);
        attachmentInfo.setAttachmentUrl(childPath+"/" + cId + "/" + fileName);
        attachmentInfo.setModifyPerson(userName);
        attachmentInfo.setModifyTime(new Date());
        attachmentInfo.setType(type);
        attachmentInfo.setcId(cId);
        attachmentInfoMapper.deleteFileRecord(attachmentInfo);
        if (attachmentInfoMapper.insert(attachmentInfo)!=1){
            return "文件入库失败，请再次上传";
        }else{
            try {
                return WebToolUtils.getLocalIP() + ":" + port + context_path + "/" + uploadFileMappingUrl + attachmentInfo.getAttachmentUrl();
            }catch (UnknownHostException | SocketException e){
                log.error(e.getMessage(), e);
                return "上传失败";
            }
        }

        //return "上传成功";

    }
}
